package com.member.gateway.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

@Component
public class TokenFilter implements GlobalFilter {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String peth = request.getPath().toString();
        if (peth.startsWith("/user/sendSms") || peth.startsWith("/provider/member/login")) {
            return chain.filter(exchange);
        }
        //设置白名单
//        String ip = request.getRemoteAddress().toString();
//        if (ip.contains("168")){
//            return chain.filter(exchange);
//        }

        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            return response.setComplete();
        }
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey("xft-ymt")
                    .parseClaimsJws(token)
                    .getBody();
            String uid = (String) claims.get("uid");
//            Integer roleid = (Integer) claims.get("roleid");

            redisTemplate.opsForValue().set(uid+"token",token,30,TimeUnit.MINUTES);
            return chain.filter(exchange);
        } catch (Exception e) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }
}
